package com.hrzyit.whistle.ui.activity

import android.Manifest
import android.annotation.TargetApi
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.hrzyit.base.common.AppManager
import com.hrzyit.base.ext.dip2px
import com.hrzyit.base.ext.onClick
import com.hrzyit.base.ui.activity.BaseMvpActivity
import com.hrzyit.base.ui.adapter.BaseGridSpacingItemDecoration
import com.hrzyit.base.ui.adapter.BaseRecyclerViewAdapter
import com.hrzyit.base.utils.AppPrefsUtils
import com.hrzyit.base.widgets.MainPageButton
import com.hrzyit.provider.common.ProviderConstant
import com.hrzyit.provider.common.isLogin
import com.hrzyit.provider.routers.RouterPath
import com.hrzyit.whistle.R
import com.hrzyit.whistle.presenter.MainPresenter
import com.hrzyit.whistle.ui.adapter.MainPageFuncButtonAdapter
import com.hrzyit.whistle.user.utils.UserPrefsUtils
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.toast

/**
 * 首页界面
 */
@Route(path = RouterPath.WhistleApp.PATH_MAIN)
class MainActivity : BaseMvpActivity<MainPresenter>() {

    // 双击间隔时间：秒
    private var pressTime: Long = 0

    var permissionInfo: String? = null

    private val sdkPermissionRequest: Int = 27

    // 按钮集合
    private lateinit var buttonList: MutableList<MainPageButton>

    // 首页功能按钮适配器
    private lateinit var mainButtonAdapter: MainPageFuncButtonAdapter


    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)


        // 检查是否已登录，若未登录跳转到登录页面
        when (isLogin()) {
            true -> {
                initView()
            }
            else -> {
                // 跳转到登录页
                ARouter.getInstance().build(RouterPath.UserCenter.PATH_LOGIN)
                    .navigation()
            }
        }
    }


    private fun initView() {

        // 初始化当前登录用户信息
        mUserNameTv.text = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_NAME)

        // 根据案件状态显示按钮
        val buttonLayoutManager = GridLayoutManager(this, 4)

        mMainPageFuncBtnRv.layoutManager = buttonLayoutManager
        mMainPageFuncBtnRv.addItemDecoration(
            BaseGridSpacingItemDecoration(
                4, this.dip2px(20.0f), this.dip2px(25.0f), false
            )
        )
        mMainPageFuncBtnRv.setHasFixedSize(true)

        mainButtonAdapter = MainPageFuncButtonAdapter(this)
        mMainPageFuncBtnRv.adapter = mainButtonAdapter

        mainButtonAdapter.setOnItemClickListener(object : BaseRecyclerViewAdapter.OnItemClickListener<MainPageButton> {
            override fun onItemClick(view: View, item: MainPageButton?, position: Int) {
                when (item?.id) {
                    R.id.mSummaryCaseTv -> {
                        // 案件汇总
                        ARouter.getInstance().build(RouterPath.CasesCenter.PATH_SUMMARY_CASE)
                            .navigation()
                    }
                    R.id.mPatrolCaseTv -> {
                        // 网格案件
                        ARouter.getInstance().build(RouterPath.CasesCenter.PATH_PATROL_CASE)
                            .navigation()
                    }
                    R.id.mWhistleCaseTv -> {
                        // 吹哨案件
                        ARouter.getInstance().build(RouterPath.CasesCenter.PATH_WHISTLE_CASE)
                            .navigation()
                    }
                    R.id.mComplaintTv -> {
                        // 12345案件
                        ARouter.getInstance().build(RouterPath.CasesCenter.PATH_COMPLAIN_CASE)
                            .navigation()

                    }
                    R.id.mRegisterCaseTv -> {
                        // 建立案件
                        ARouter.getInstance().build(RouterPath.CasesCenter.PATH_REGISTER_CASE)
                            .navigation()
                    }
                    R.id.mTransferCaseTv -> {
                        // 批转案件
                        ARouter.getInstance().build(RouterPath.CasesCenter.PATH_TRANSFER_CASE)
                            .navigation()
                    }
                    R.id.mOvertimeCaseTv -> {
                        // 超时案件
//                ARouter.getInstance().build(RouterPath.CasesCenter.PATH_OVER_TIME_CASE)
//                    .navigation()
                    }
                    R.id.mContactListTv -> {
                        // 联络单位界面
                        ARouter.getInstance().build(RouterPath.CommunicationCenter.PATH_COMM_MAIN).navigation()
                    }
                    R.id.mDataStatisticsTv -> {
                        // 数据统计
                        toast("申请结案开发中")
//                        ARouter.getInstance().build("/im/main").navigation()
                    }
                    R.id.mApplyCloseCaseTv -> {
                        // 申请结案
                         toast("申请结案开发中")
//                ARouter.getInstance().build(RouterPath.CasesCenter.PATH_APPLY_CLOSE)
//                    .navigation()

                    }
                    R.id.mApplyDelayTv -> {
                        // 申请延期
//                ARouter.getInstance().build(RouterPath.CasesCenter.PATH_APPLY_DELAY)
//                    .navigation()
                        toast("申请结案开发中")
                    }
                }
            }
        }) // end setOnItemClick

        // 查看个人信息
        mUserNameTv.onClick{
            // 查看个人信息
            ARouter.getInstance().build(RouterPath.UserCenter.PATH_USER_INFO).navigation()
        }

        // 创建按钮
        buildFuncButtonList()

    }



    /**
     * 生成首页功能按钮
     */
    private fun buildFuncButtonList() {

        buttonList = mutableListOf()

        val mSummaryCaseTv = MainPageButton(
            R.id.mSummaryCaseTv,
            this.applicationContext.getString(R.string.index_icon_case_summary),
            ContextCompat.getDrawable(this, R.drawable.shouye_icon_ajhz)
        )
        val mPatrolCaseTv = MainPageButton(
            R.id.mPatrolCaseTv,
            this.applicationContext.getString(R.string.index_icon_patrol_case),
            ContextCompat.getDrawable(this, R.drawable.shouye_icon_xcaj)
        )

        val mWhistleCaseTv = MainPageButton(
            R.id.mWhistleCaseTv,
            this.applicationContext.getString(R.string.index_icon_whistle_case),
            ContextCompat.getDrawable(
                this, R.drawable.shouye_icon_csaj
            )
        )

        val mComplaintTv = MainPageButton(
            R.id.mComplaintTv,
            this.applicationContext.getString(R.string.index_icon_complaint),
            ContextCompat.getDrawable(
                this, R.drawable.shouye_icon_tsaj
            )
        )

        val mRegisterCaseTv = MainPageButton(
            R.id.mRegisterCaseTv,
            this.applicationContext.getString(R.string.index_icon_case_register),
            ContextCompat.getDrawable(
                this, R.drawable.shouye_icon_xjaj
            )
        )

        val mTransferCaseTv = MainPageButton(
            R.id.mTransferCaseTv,
            this.applicationContext.getString(R.string.index_icon_transfer_case),
            ContextCompat.getDrawable(
                this, R.drawable.shouye_icon_pzaj
            )
        )

        val mOvertimeCaseTv = MainPageButton(
            R.id.mOvertimeCaseTv,
            this.applicationContext.getString(R.string.index_icon_overtime_case),
            ContextCompat.getDrawable(
                this, R.drawable.shouye_icon_csaj_1
            )
        )

        val mContactListTv = MainPageButton(
            R.id.mContactListTv,
            this.applicationContext.getString(R.string.index_icon_contact_list),
            ContextCompat.getDrawable(
                this, R.drawable.shouye_icon_llmd
            )
        )

        val mDataStatisticsTv = MainPageButton(
            R.id.mDataStatisticsTv,
            this.applicationContext.getString(R.string.index_icon_data_statistics),
            ContextCompat.getDrawable(
                this, R.drawable.shouye_icon_xjtj
            )
        )

        val mApplyCloseCaseTv = MainPageButton(
            R.id.mApplyCloseCaseTv,
            this.applicationContext.getString(R.string.index_icon_apply_close_case),
            ContextCompat.getDrawable(
                this, R.drawable.shouye_icon_sqja
            )
        )

        val mApplyDelayTv = MainPageButton(
            R.id.mApplyDelayTv,
            this.applicationContext.getString(R.string.index_icon_apply_delay),
            ContextCompat.getDrawable(
                this, R.drawable.shouye_icon_sqyq
            )
        )

        // 根据角色显示按钮
        when (AppPrefsUtils.getLong(ProviderConstant.KEY_SP_USER_ROLE_ID)) {
            16L -> {
                // 处置员(第四方)
                buttonList.add(mSummaryCaseTv)
                buttonList.add(mPatrolCaseTv)
                buttonList.add(mComplaintTv)
                buttonList.add(mTransferCaseTv)
                buttonList.add(mContactListTv)
            }
            15L -> {
                // 外勤员(第三方)
                buttonList.add(mSummaryCaseTv)
                buttonList.add(mPatrolCaseTv)
                buttonList.add(mRegisterCaseTv)
                buttonList.add(mContactListTv)
            }
            21L, 22L -> {
                // 办事员
                buttonList.add(mSummaryCaseTv)
                buttonList.add(mPatrolCaseTv)
                buttonList.add(mComplaintTv)
                buttonList.add(mTransferCaseTv)

                buttonList.add(mWhistleCaseTv)
                buttonList.add(mOvertimeCaseTv)
                buttonList.add(mContactListTv)

                buttonList.add(mDataStatisticsTv)
                buttonList.add(mApplyCloseCaseTv)
                buttonList.add(mApplyDelayTv)

            }
            19L, 20L -> {
                // 社区、分管负责人
                buttonList.add(mSummaryCaseTv)
                buttonList.add(mPatrolCaseTv)
                buttonList.add(mComplaintTv)
                buttonList.add(mTransferCaseTv)

                buttonList.add(mWhistleCaseTv)
                buttonList.add(mOvertimeCaseTv)
                buttonList.add(mContactListTv)

                buttonList.add(mDataStatisticsTv)
                buttonList.add(mApplyCloseCaseTv)
                buttonList.add(mApplyDelayTv)
            }
            18L -> {
                // 街道领导
                buttonList.add(mSummaryCaseTv)
                buttonList.add(mPatrolCaseTv)
                buttonList.add(mComplaintTv)
                buttonList.add(mTransferCaseTv)

                buttonList.add(mWhistleCaseTv)
                buttonList.add(mOvertimeCaseTv)
                buttonList.add(mContactListTv)

                buttonList.add(mApplyCloseCaseTv)
                buttonList.add(mApplyDelayTv)
            }

        }

        mainButtonAdapter.setData(buttonList)

    }

    /**
     * Dagger2 注入
     */
    override fun injectComponent() {

    }

    /**
     * 重写Back事件，双击退出
     */
    override fun onBackPressed() {
        val time = System.currentTimeMillis()
        if (time - pressTime > 2000) {
            toast("再按一次退出程序")
            pressTime = time
        } else {
            UserPrefsUtils.clearInfo()
            AppManager.instance.exitApp(this)
        }
    }

    // 动态权限 ------------------

    @TargetApi(23)
    private fun getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val permissions = ArrayList<String>()
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION)
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION)
            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
             */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n"
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n"
            }

            if (permissions.size > 0) {
                requestPermissions(permissions.toArray(arrayOfNulls(permissions.size)), sdkPermissionRequest)
            }
        }
    }


    /**
     * 添加动态权限
     */
    @TargetApi(23)
    private fun addPermission(permissionsList: ArrayList<String>, permission: String): Boolean {
        return if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                true
            } else {
                permissionsList.add(permission)
                false
            }

        } else {
            true
        }
    }

    /**
     * 申请动态权限结果
     */
    @TargetApi(23)
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
}
